#include "charging.h"


#if (CONFIG_USING_CHARGER == 1)

void charging_init(void)
{
    /* ensure charger is disabled, configure ISET and TIMEOUT */
    /* Charging timeout, TIMEOUT_08H 8H, TIMEOUT_12H 12H, TIMEOUT_24H 24H, TIMEOUT_48H 48H */
    WRITE_REG(CHGCON0, TIMEOUT_48H);

    /* configure VSET, VLPEN, TLPEN and ISTOPEN */
    WRITE_REG(CHGCON1, CONFIG_CHARGER_VSET | VLPEN | TLPEN | ISTOPEN);
    
    /* configure VLPSET, TLPSET, VSTOP and ISTOP */
    WRITE_REG(CHGCON2, VLPSET_4V4 | TLPSET_105 | CONFIG_CHARGER_VSTOP | ISTOP_5);

    MODIFY_REG(CHGCON3, CHGMOD_CLR, CHGMOD);
    /* 1.5V force charger enable */
    // SET_BIT(CHGCON0, CHG_EN)
    // CLEAR_BIT(CHGCON1, CLR_VSET);
    // SET_BIT(CHGCON1, CONFIG_CHARGER_VSET);

/* If enable "Re-Charger" function.
 *    ONLY for IC B+ version
 *    ONLY for CONFIG_BAT_FULL_VOLTAGE >= 4.2V
 */
#if (CONFIG_BAT_FULL_VOLTAGE >= 4200 && CONFIG_CHARGER_USING_RCHG == 1)
    if (sys_get_version() > 0)
        MODIFY_REG(CHGCON4, RCHG, RCHG);
#else
    CLEAR_BIT(CHGCON4, RCHG);
#endif
}

/**
 * @brief If the charging module is enabled, the charging current is adjusted
 * 
 * Each time the charging current is adjusted by one gear (45ma), 
 * it will stop increasing if it is greater than the set value. 
 * If the charging module is off, set the charging current to the default value of 000 (45ma)
 * 
 * @param iset 
 */
void charging_current_set(uint8_t iset)
{
    static uint8_t charging_iset_cnt;
    
    if (IS_CHARGING_ENABLE()) {
        if (CHARGING_ISET_READ() < iset) {
            charging_iset_cnt++;
            CHARGING_ISET(charging_iset_cnt);
        } else if (CHARGING_ISET_READ() >= iset) {
            charging_iset_cnt = 0;
            CHARGING_ISET(iset);
        }
    } else {
        charging_iset_cnt = 0;
        CHARGING_ISET(charging_iset_cnt);
    }
}

void charging_exit(void)
{
    /* ensure charger is disabled */
    CHARGING_DISABLE();
}

#endif